package cn.imvc.app.jobs;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import cn.imvc.app.commons.SystemConfig;
import cn.imvc.app.domains.OrderState;
import cn.imvc.app.entities.GoodsOrder;
import cn.imvc.app.models.GoodsOrderModel;
@DisallowConcurrentExecution
public class AutomaticConfirmOrderQuarz{
	private static final Logger log = Logger.getLogger(AutomaticConfirmOrderQuarz.class);
	@Autowired
	private GoodsOrderModel goodsOrderModel;
	@Autowired
	private SystemConfig systemConfig;

	/**
	 * 自动确认订单完成
	 */
	public void automaticConfirmOrder(JobExecutionContext context) {
		Calendar calendar = Calendar.getInstance();// 日历对象
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		List<GoodsOrder> goodsOrderList = goodsOrderModel.findByStateAndCreatedAtLessThan(OrderState.Receipt.getValue(),calendar.getTime());
		for (GoodsOrder goodsOrder : goodsOrderList) {
			try {
				Date receiptTime = goodsOrder.getOrderStorage().getReceiptTime();
				Date nowTime = new Date();
				if (nowTime.getTime() - receiptTime.getTime() >= (systemConfig.getReceiptRefundOfDays() * 24 * 60 * 60 * 1000)) {
					goodsOrder.setState(OrderState.Finish.getValue());
					goodsOrder.setUpdatedAt(new Date());
					goodsOrder.setFinishTime(new Date());
					goodsOrderModel.update(goodsOrder);
				} 
			} catch (Exception e) {
				log.error(e.toString());
			}
			}
		
		
		Calendar calendar1 = Calendar.getInstance();// 日历对象
		calendar1.add(Calendar.DAY_OF_MONTH, -14);
		List<GoodsOrder> goodsOrderList1 = goodsOrderModel.findByStateAndCreatedAtLessThan(OrderState.SystemReceipt.getValue(),calendar1.getTime());
		for (GoodsOrder goodsOrder : goodsOrderList1) {
			try {
					goodsOrder.setState(OrderState.Finish.getValue());
					goodsOrder.setUpdatedAt(new Date());
					goodsOrder.setFinishTime(new Date());
					goodsOrderModel.update(goodsOrder);
			} catch (Exception e) {
				log.error(e.toString());
			}
			}
		System.out.println("自动确认订单完成完毕！！！");
		
    }
}
